<?php

namespace Partner\Controller;

use Utuo\BackgroundController;

class WechatController extends BackgroundController {
	// 初始化
	public function _initialize() {
		$this->setControllerTitle ( '微信公众平台设置' );
		$this->setActionTitle ( 'index', '微信公众平台设置' );
	}
	
	// 微信公众平台设置
	public function indexAction() {
		$d = D ( 'Wechat' );
		$wechat = $d->where("pid=%d", $this->aid)->find();
		if (! $wechat) {
			if ($d->data ( array (
					'pid' => $this->aid,
					'token' => ''
			) )->add ()) {
				$wechat = $d->where("pid=%d", $this->aid)->find();
			} else {
				$this->error ( "添加数据失败" );
			}
		}
		$wechat ['url'] = $this->getApiUrl ();
		$this->assign ( 'wechat', $wechat );
		$this->display ();
	}
	
	// 更新接口设置
	public function indexPostAction() {
		$d = D ( "Wechat" );
		if ($d->create ()) {
			if (false !== $d->save ()) {
				$this->ajaxSuccess ();
			} else {
				$this->ajaxError ( $d->getError () );
			}
		} else {
			$this->ajaxError ( $d->getError () );
		}
	}
	
	// 获取接口URL
	protected function getApiUrl() {
		$id = $this->aid;
		$baseUrl = sprintf ( 'http://%s%s', $_SERVER ['HTTP_HOST'], $_SERVER ['SCRIPT_NAME'] );
		$apiUrl = $baseUrl . '/Api/ShopWechat/index/id/' . $id;
		return $apiUrl;
	}
	
	// 获取接口TOKEN
	protected function getApiToken() {
		$token = $this->aid . rand ( 100000, 999999 );
		$token = dechex ( $token );
		return $token;
	}
	
	// 更新TOKEN
	public function updateTokenPostAction() {
		$token = $this->getApiToken ();
		if (D ( "Wechat" )->where ( "pid={$this->aid}" )->setField ( "token", $token )) {
			$this->ajaxSuccess ( '更新Token成功，请到微信公众平台后台重新绑定', array (
					'token' => $token 
			) );
		} else {
			$this->ajaxError ( "更新token失败，请重试" );
		}
	}
}